package com.example.mq.mqserver.core;

import com.example.mq.common.ConsumerEnv;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class MSGQueue {
    private String name;
    private boolean durable=false;
    private boolean exclusive=false;
    private boolean autoDelete=false;
    private Map<String,Object> arguments=new HashMap<>();
    private List<ConsumerEnv> consumerEnvList=new ArrayList<>();
    private AtomicInteger consumerSeq=new AtomicInteger();

    public void addConsumerEnv(ConsumerEnv consumerEnv){
        consumerEnvList.add(consumerEnv);
    }

    public ConsumerEnv chooseConsumer(){
        if(consumerEnvList.size()==0){
            return null;
        }
        int index=consumerSeq.get()%consumerEnvList.size();
        consumerSeq.getAndIncrement();
        return consumerEnvList.get(index);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isExclusive() {
        return exclusive;
    }

    public void setExclusive(boolean exclusive) {
        this.exclusive = exclusive;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    public String getArguments() {
        ObjectMapper objectMapper=new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    public void setArguments(String ArgumentsJson) {
        ObjectMapper objectMapper=new ObjectMapper();
        try {
            this.arguments=objectMapper.readValue(ArgumentsJson,new TypeReference<HashMap<String,Object>>(){});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public Object getArguments(String key){
        return arguments.get(key);
    }

    public void setArguments(String key,Object value){
        arguments.put(key,value);
    }

    public void setArguments(Map<String,Object> arguments){
        this.arguments=arguments;
    }
}
